using AudioStudio;
using com.youzu.warh.protocol;
using LogSystem;
using System;
using System.Collections.Generic;
using UnityEngine;
using Yoozoo.Gameplay.Liberty.AI;
using Yoozoo.Gameplay.Liberty.Pool;

namespace Yoozoo.Gameplay.Liberty
{
    /// <summary>
    /// 道具物品
    /// </summary>
    public class PropItem : MonoBehaviour
    {
        // 创建掉落物回调
        public static Action<PropItem> OnPropItemCreate;
        // 销毁掉落物回调
        public static Action<PropItem> OnPropItemDestroy;
        // 拾取掉落物回调
        public static Action<int, int, long,PropItem> OnPropItemTaken;

        public static long AddUid = 1000000;
        // 道具容器
        private static readonly Dictionary<int, int> k_ContainerIDs = new Dictionary<int, int>
        {
            {1, 1021},
            {2, 1022},
            {3, 1023},
            {4, 1024},
            {5, 1025},
        };
        
        /// <summary>
        /// 创建掉落物
        /// </summary>
        /// <param name="itemId"></param>
        /// <param name="quality"></param>
        /// <param name="count"></param>
        /// <returns></returns>
        public static PropItem CreatePropItem(int id, bool openCollider = true)
        {
            PbItemConfig itemConfig = LibertyConfigManager.GetInstance().GetItemDataConfig(id);

            if (itemConfig != null)
            {
                int containerId = 0;
                if (k_ContainerIDs.TryGetValue(itemConfig.quality, out containerId))
                {
                    var container = LibertyPoolMgr.GetInstance().GetEffectObject(containerId);
                    container.gameObject.SetActive(true);
                    PropItem propItem = container.GetComponent<PropItem>();
                    propItem.SetData(itemConfig, openCollider);
                    OnPropItemCreate?.Invoke(propItem);
                    return propItem;
                }
            }
            else
            {
                Debug.LogError(LogModule.LibertySceneBattle,"掉落道具配置找不到 Id：" + id);
            }
            return null;
        }

        /// <summary>
        /// 删除掉落物
        /// </summary>
        /// <param name="itemId"></param>
        /// <param name="quality"></param>
        /// <param name="count"></param>
        /// <param name="propItem"></param>
        public static void DestroyPropItem(PropItem propItem)
        {
            int containerId = 0;
            if (k_ContainerIDs.TryGetValue(propItem._quality, out containerId))
            {
                OnPropItemDestroy?.Invoke(propItem);
                propItem.Recycle();
                LibertyPoolMgr.GetInstance().RecycleEffect(containerId, propItem.transform);
            }
        }
        
        // Collider
        [SerializeField]
        private Collider _collider;
        // Container节点
        [SerializeField]
        private Transform _containerTransform;
        // 每秒旋转多少度
        [SerializeField]
        private float _rotationPerSecond = 60;
        // 动画
        [SerializeField]
        private Animation _animation;
        // 消失动画名
        [SerializeField]
        private string _disappearAnimationName = "ani_dimian_glow_xiaoshi";

        // 销毁动画播放时长
        private float _disappearDuration = 22f;
        // 自动销毁时长
        private float _existDuration = -1;//25;
        // 销毁计时器
        private float _existTimer = 0;
        // item节点
        private Transform _itemTransform;
        // 模型资源ID
        private int _itemResID;
        
        // Data
        [SerializeField]
        private int _id;

        public int ItemId => _id;
        public long UID;
        private int _quality => _itemConfig.quality;
        private PbItemConfig _itemConfig;
        private Transform playerTransform;
        public PbItemConfig ItemConfig => _itemConfig;
        public int ItemType => _itemConfig.type;

        public int BindId => _itemConfig.bind_id;
        // 是否已经被拾取
        public bool HasBeenTaken => _itemConfig == null;

        /// <summary>
        /// 设置PropItem数据
        /// </summary>
        /// <param name="itemId"></param>
        /// <param name="quality"></param>
        /// <param name="count"></param>
        void SetData(PbItemConfig itemConfig, bool openCollider)
        {
            this._id = itemConfig.id;
            this._itemConfig = itemConfig;
            this._existTimer = 0;
            UID = ++AddUid;
            _itemResID = itemConfig.model;
            _itemTransform = LibertyPoolMgr.GetInstance().GetEffectObject(_itemResID);
            if (_itemTransform != null)
            {
                _itemTransform.parent = _containerTransform;
                _itemTransform.localPosition = Vector3.zero;
                _itemTransform.localRotation = Quaternion.identity;
                _itemTransform.gameObject.SetActive(true);
            }
            
            // 设置触发器开关
            _collider.enabled = openCollider;
            // 重置动画
            _animation.Play(_disappearAnimationName);
            var state = _animation[_disappearAnimationName];
            state.time = 0;
            _animation.Sample();
            _animation.Stop();
            _animation.enabled = false;

            playerTransform = LibertyAIUtils.GetPlayerEntity().viewer.animator.transform;
        }

        /// <summary>
        /// 打开触发器
        /// </summary>
        public void OpenCollider()
        {
            _collider.enabled = true;
        }
        
        /// <summary>
        /// 关闭触发器
        /// </summary>
        public void CloseCollider()
        {
            _collider.enabled = false;
        }

        /// <summary>
        /// 拾取
        /// </summary>
        public void OnTake(AIEntity aiEntity, GameObject collider)
        {
            //根据道具的配置决定是否能拾取
            if (_itemConfig.pick_priority == 1)//只有主角可拾取
            {
                if (aiEntity.id != LibertyAIUtils.PLAYER_AI_ID)
                {
                    return;
                }
            }

            if (_itemConfig.pick_priority == 2) //仅我方阵营能拾取
            {
                if (!collider.CompareTag("Teammate") && !collider.CompareTag("Player"))
                {
                    return;
                }
            }if (_itemConfig.pick_priority == 3)//仅npc能拾取
            {
                if (aiEntity.id == LibertyAIUtils.PLAYER_AI_ID)
                {
                    return;
                }
            }
            // 使用道具
            switch ((ItemFuncType)_itemConfig.item_func)
            {
                case ItemFuncType.AddHealth:
                    {
                        // 加血
                        aiEntity.data.hp = Mathf.Min(aiEntity.data.hp+_itemConfig.parameter_01, aiEntity.propertyDataConfig.hp);
                    }
                    break;
                
                case ItemFuncType.AddBullet:
                    {
                        // 加子弹
                        aiEntity.WeaponSystem.AddWeapon(_itemConfig.bind_id, _itemConfig.parameter_01);
                        // 玩家自动切换武器
                        if (aiEntity.id == LibertyAIUtils.PLAYER_AI_ID)
                        {
                            PbWeaponDataConfig weaponDataConfig = LibertyConfigManager.GetInstance().GetWeaponDataConfig(_itemConfig.bind_id);
                            if (weaponDataConfig != null && weaponDataConfig.battle_state != (int)BattleState.Bomb)
                            {
                                LibertyAIUtils.PlayerController.EuipAndSwitchWeapon(_itemConfig.bind_id);
                            }
                        }
                    }
                    break;

                
                case ItemFuncType.ArenaCup: // 格斗赛奖杯
                    break;
                
                default:
                    {
                        UnityEngine.Debug.LogError($"未处理的道具类型: {_itemConfig.item_func}");   
                    }
                    break;
            }

            // 播放拾取特效
            if (aiEntity.battleAgent && _itemConfig.effect>0)
            {
                aiEntity.battleAgent.ShowTakePropItemEffect(_itemConfig.effect);
            }
            // 播放拾取音效
            if (aiEntity.id == LibertyAIUtils.PLAYER_AI_ID)
            {
                AudioManager.PlaySound("SandBox_Player_Pickitem", LibertyAIUtils.PlayerController.playerEntity.AIEntity.battleAgent.gameObject);
            }
            
            // 拾取回调
            OnPropItemTaken?.Invoke(_id, aiEntity.id,UID,this);
            
            // 销毁道具
            PropItem.DestroyPropItem(this);
        }

        private int lodCheckCount = 0;

        void Update()
        {
            Vector3 localEulerAngles = _containerTransform.localEulerAngles;
            localEulerAngles.y += _rotationPerSecond * Time.deltaTime;
            _containerTransform.localEulerAngles = localEulerAngles;

            if (_existDuration > 0)
            {
                _existTimer += Time.deltaTime;
                if (_existTimer >= _disappearDuration)
                {
                    // 播放消失动画
                    if (!_animation.enabled)
                    {
                        _animation.enabled = true;
                        _animation.Play(_disappearAnimationName);
                    }
                }
                if (_existTimer >= _existDuration)
                {
                    // 销毁道具
                    PropItem.DestroyPropItem(this);
                }
            }

            lodCheckCount++;
            if (lodCheckCount >= 10)
            {
                lodCheckCount = 0;

                var directionToPlayer = Vector3.zero;
                var playerPosition = playerTransform.position;
                var npcPosition = transform.position;
                directionToPlayer.x = playerPosition.x - npcPosition.x;
                directionToPlayer.z = playerPosition.z - npcPosition.z;
                float distanceToPlayer = directionToPlayer.magnitude;
                bool isItemVisible = distanceToPlayer < LibertyConst.NpcLod0Radius;

                if (_itemTransform != null)
                {
                    _itemTransform.gameObject.SetActive(isItemVisible);
                }
            }
        }
        
        /// <summary>
        /// 回收PropItem
        /// </summary>
        void Recycle()
        {
            if (_itemTransform)
            {
                LibertyPoolMgr.GetInstance().RecycleEffect(_itemResID, _itemTransform);

                _itemTransform = null;
                _itemResID = 0;
                _id = 0;
                UID = 0;
                _itemConfig = null;
            }
        }

        public bool GetItemCanPick(SideType sideType)
        {
            if (_itemConfig.pick_priority == 1)//只有主角拾取
            {
                return sideType == SideType.Player;
            }

            if (_itemConfig.pick_priority == 2)//仅我方能拾取
            {
                return sideType == SideType.Player || sideType == SideType.Teammate;
            }

            if (_itemConfig.pick_priority == 3)//仅npc能拾取
            {
                return sideType != SideType.Player;
            }

            return true;
        }

    }
}
